import { createNamespacedHelpers } from 'vuex'
const { mapGetters, mapActions } = createNamespacedHelpers('user')
import { cloneDeep } from '@/utils/lodash/Lang'
// 性别选项
const genderOptions = [
  { label: '男', value: 1 },
  { label: '女', value: 2 },
]
/**
 * 用户列表
 */
export default {
  name: 'List',
  data() {
    return {
      form: {
        nickName: '', // 昵称
        gender: '', // 性别
      },  // 表单
      dialogType: 'add',  // 对话框类型 add | edit
      dialogVisible: false, // 对话框状态
      rules: {
        nickName: [
          { required: true, message: '请输入昵称', trigger: ['blur'] }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: ['blur'] }
        ],
      },
    }
  },
  computed: {
    ...mapGetters(['collection', 'total', 'pagination']),
  },
  methods: {
    ...mapActions(['getCollection', 'updateDocument', 'deleteDocument', 'createDocument', 'updateCollection']),
    setDialogVisible(flag) {
      this.dialogVisible = flag
    },
    setDialogType(str) {
      this.dialogType = str
    },
  },
  async mounted() {
    await this.getCollection()
  },
  render(h) {
    /** 操作按钮栏 */
    const HandleBar = () => {
      // 重置表单
      const resetForm = () => {
        this.form = {
          nickName: '', // 昵称
          gender: '', // 性别
        }
        this.$refs.form.resetFields()
      }
      // 添加
      const addForm = () => {
        this.setDialogType('add')
        this.setDialogVisible(true)
        this.$nextTick(() => resetForm())
      }
      return (
        <el-card>
          <el-button type="primary" icon="el-icon-plus" onClick={addForm}>添加用户</el-button>
        </el-card>
      )
    }
    
    /** 表格 */
    const Table = () => {
      // 编辑
      const editForm = (form) => {
        this.setDialogType('edit')
        this.setDialogVisible(true)
        this.form = cloneDeep(form)
      }
      // 删除
      const deleteForm = async(form) => {
        await this.deleteDocument({ id: form.id })
        this.$message({
          message: '删除成功！',
          type: 'success'
        })
      }
      // 性别插槽
      const genderSlot = {
        default: (scope) => {
          const item = genderOptions.find(v => v.value === scope.row.gender)
          const type = item ? item.value === 2 ? 'success' : '' : 'info'
          return <el-tag type={type}>{item ? item.label : '未知'}</el-tag>
        }
      }
      // 操作插槽
      const handleSlot = {
        default: (scope) => {
          return (
            <div>
              <el-button type="text" onClick={() => editForm(scope.row)}>编辑</el-button>
              <el-popconfirm
                confirmButtonText='确定'
                cancelButtonText='取消'
                icon="el-icon-info"
                iconColor="red"
                title="确认要删除这一项吗？"
                onOnConfirm={() => deleteForm(scope.row)}
              >
                <el-button slot="reference" type="text" style={{ color: '#F56C6C', marginLeft: '10px' }}>删除</el-button>
              </el-popconfirm>
            </div>
          )
        }
      }
      return (
        <el-card>
          <el-table ref="table" data={this.collection} row-key="id">
            <el-table-column prop="nickName" label="昵称" min-width="200" fixed />
            <el-table-column prop="id" label="id" min-width="200" />
            <el-table-column label="性别" scopedSlots={genderSlot} min-width="200">
              <slot />
            </el-table-column>
            <el-table-column label="操作" scopedSlots={handleSlot} min-width="200" fixed="right">
              <slot />
            </el-table-column>
          </el-table>
          <Pagination total={this.total} pagination={this.pagination} onChange={this.getCollection} />
        </el-card>
      )
    }

    /** 表单对话框 */
    const FormDialog = () => {
      // 关闭
      const onClose = () => {
        this.setDialogVisible(false)
      }
      // 提交
      const submitForm = () => {
        const callback = async(valid) => {
          // 未通过校验
          if (!valid) {
            return false
          }
          let form = cloneDeep(this.form)
          // 添加
          if (this.dialogType === 'add') {
            await this.createDocument(form)
            this.setDialogVisible(false)
            this.$message({
              message: '添加成功！',
              type: 'success'
            })
            return
          }
          // 编辑
          await this.updateDocument(form)
          this.setDialogVisible(false)
          this.$message({
            message: '修改成功！',
            type: 'success'
          })
        }
        this.$refs.form.validate(callback)
      }
      // 监听键盘
      const onKeyup = ({ key }) => {
        if (key !== 'Enter') return
        submitForm()
      }
      return (
        <el-dialog
          title={this.dialogType === 'add' ? '添加用户' : '编辑用户'}
          visible={this.dialogVisible}
          onClose={onClose}
          width="580px"
        >
          <el-form ref="form" label-width="80px" props={{ model: this.form, rules: this.rules }}>
            <el-form-item prop="nickName" label="昵称">
              <el-input
                value={this.form.nickName}
                onInput={v => this.form.nickName = v}
                placeholder="请输入昵称"
                nativeOnKeyup={onKeyup}
              />
            </el-form-item>
            <el-form-item prop="gender" label="性别">
              {
                genderOptions.map(v => (
                  <el-radio
                    value={this.form.gender}
                    onInput={v => this.form.gender = v}
                    label={v.value}
                  >
                    {v.label}
                  </el-radio>
                ))
              }
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button onClick={onClose}>取消</el-button>
            <el-button type="primary" onClick={submitForm}>确定</el-button>
          </div>
        </el-dialog>
      )
    }

    return (
      <div class="user-list">
        <HandleBar />
        <Table />
        <FormDialog />
      </div>
    )
  }
}